package com.learning.imoney;

import android.annotation.SuppressLint;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.datepicker.CalendarConstraints;
import com.google.android.material.datepicker.DateValidatorPointForward;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener;
import com.learning.imoney.db.Bill;
import com.learning.imoney.db.DataBaseBill;

import android.database.Cursor;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class OverviewFragment extends Fragment implements View.OnClickListener {
    private RecyclerView recyclerView;
    private BillAdapter billAdapter;
    private Button dateBtn,selectedBtn;
    private TextView tvMonth,tvIn,tvOut;
    private List<Bill> billList;
    private SQLiteDatabase db;
    DataBaseBill mhelper;
    private String selectedDate;
    private int currentYear = Calendar.getInstance().get(Calendar.YEAR);
    private int currentMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
    private int billType = -1;


    @SuppressLint({"MissingInflatedId", "DefaultLocale"})
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_overview, container, false);
        // 初始化RecyclerView
        recyclerView = view.findViewById(R.id.rv_bills);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        //
        dateBtn = view.findViewById(R.id.btn_select_date);
        selectedDate = String.format("%04d-%02d", currentYear, currentMonth);
        dateBtn.setText(selectedDate);
        dateBtn.setOnClickListener(this);
        selectedBtn = view.findViewById(R.id.btn_select);
        selectedBtn.setOnClickListener(this);
        //
        tvMonth = view.findViewById(R.id.select_month);
        tvMonth.setText(currentMonth + "月");
        //
        tvIn = view.findViewById(R.id.tv_in);
        tvOut = view.findViewById(R.id.tv_out);

        //
        mhelper = new DataBaseBill(getActivity());//实例化数据库帮助类对象
        db = mhelper.getWritableDatabase();//获取数据库的读写权限

        // 初始化账单数据
//        billList = new ArrayList<>();
//        billList.add(new Bill(1, 1000.00, "2024-10-10", "工资"));
//        billList.add(new Bill(0, 200.00, "2024-10-12", "餐饮"));
//        billList.add(new Bill(0, 150.00, "2024-10-13", "购物"));
//        List<Bill> allBill = queryAllBill();
        // 动态加载或从数据库获取更多账单数据
        // 初始化适配器并设置给RecyclerView
        billList = new ArrayList<>();
        billAdapter = new BillAdapter(billList, getContext());
        recyclerView.setAdapter(billAdapter);
        loadBillData();

        return view;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_select_date) {
            showMonthYearPicker();
        } else if (v.getId() == R.id.btn_select) {
            showFilter();
        }

    }

    @SuppressLint({"Range", "SetTextI18n"})
    private void loadBillData() {
        billList.clear();
        double allIncome = 0;
        double allExpenditures = 0;
        Cursor cursor = null;
        //开始查询 参数：（实现查询的 sql 语句，条件参数）
        if (billType == -1) {
            cursor = db.rawQuery("select * from bill_info where time between ? and ? order by time desc ", new String[]{selectedDate + "-01", selectedDate + "-31"});
        } else if (billType == 1) {
            cursor = db.rawQuery("select * from bill_info where time between ? and ? and type = ? order by time desc ", new String[]{selectedDate + "-01", selectedDate + "-31", "1"});
        } else if (billType == 0) {
            cursor = db.rawQuery("select * from bill_info where time between ? and ? and type = ? order by time desc ", new String[]{selectedDate + "-01", selectedDate + "-31", "0"});
        }

        if (cursor.getCount() != 0) {//判断结果集中是否有数据，有：查询成功；无：查询失败
            Toast.makeText(getActivity(), "查询成功", Toast.LENGTH_SHORT).show();
            //循环遍历结果集，取出数据，显示出来
            while (cursor.moveToNext()) {
                int id = cursor.getInt(cursor.getColumnIndex("_id"));
                int type = cursor.getInt(cursor.getColumnIndex("type"));
                String date = cursor.getString(cursor.getColumnIndex("time"));
                String note = cursor.getString(cursor.getColumnIndex("note"));
                double money = cursor.getDouble(cursor.getColumnIndex("money"));
                billList.add(new Bill(id, type, money, date, note));
                if (type == 1) {
                    allIncome += money;
                } else if (type == 0) {
                    allExpenditures +=money;
                }
            }
            tvOut.setVisibility(View. VISIBLE);
            tvIn.setText("总收入： "+allIncome +"元");
            tvOut.setText("总支出： "+allExpenditures +"元");
        } else {
//            Toast.makeText(getActivity(), "该日没有收支", Toast.LENGTH_SHORT).show();
            tvIn.setText("本月没有收支。");
            tvOut.setVisibility(View.INVISIBLE);
        }
        // 通知适配器数据已更新
        billAdapter.notifyDataSetChanged();
    }

//    @SuppressLint("Range")
//    private List<Bill> queryAllBill() {
//        //开始查询 参数：（实现查询的 sql 语句，条件参数）
//        Cursor cursor = db.rawQuery("select * from bill_info", null);
//        List<Bill> billsAll = new ArrayList<>();
//        if (cursor.getCount() != 0) {//判断结果集中是否有数据，有：查询成功；无：查询失败
//            Toast.makeText(getActivity(), "查询成功", Toast.LENGTH_SHORT).show();
//            //循环遍历结果集，取出数据，显示出来
//            while (cursor.moveToNext()) {
//                int id  = cursor.getInt(cursor.getColumnIndex("_id"));
//                int type = cursor.getInt(cursor.getColumnIndex("type"));
//                String date = cursor.getString(cursor.getColumnIndex("time"));
//                String note = cursor.getString(cursor.getColumnIndex("note"));
//                double money = cursor.getDouble(cursor.getColumnIndex("money"));
//                billsAll.add(new Bill(id, type, money, date, note));
//            }
//        } else {
//            Toast.makeText(getActivity(), "该日没有收支", Toast.LENGTH_SHORT).show();
//        }
//        return billsAll;
//    }



    private void showMonthYearPicker() {
        // 创建BottomSheetDialog
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(requireContext());
        View bottomSheetView = getLayoutInflater().inflate(R.layout.layout_month_year_picker, null);
        bottomSheetDialog.setContentView(bottomSheetView);

        // 获取NumberPicker
        final NumberPicker npMonth = bottomSheetView.findViewById(R.id.np_month);
        final NumberPicker npYear = bottomSheetView.findViewById(R.id.np_year);
        Button btnConfirm = bottomSheetView.findViewById(R.id.btn_confirm);

        // 设置月份选择器
        npMonth.setMinValue(1);
        npMonth.setMaxValue(12);
        npMonth.setValue(currentMonth); // 默认选择当前月份

        // 设置年份选择器（范围：1900年到当前年份）

        npYear.setMinValue(1900);
        npYear.setMaxValue(currentYear);
        npYear.setValue(currentYear);  // 默认选择当前年份

        // 点击确定按钮
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onClick(View v) {
                int selectedMonth = npMonth.getValue();
                int selectedYear = npYear.getValue();

                // 显示选择的年月
                selectedDate = String.format("%04d-%02d", selectedYear, selectedMonth);
                dateBtn.setText(selectedDate);  // 更新按钮文本
                tvMonth.setText(selectedMonth + "月");


                Toast.makeText(getContext(), "选择的年月: " + selectedDate, Toast.LENGTH_SHORT).show();

                // 更新适配器持有的账单列表
                loadBillData();

                // 关闭对话框
                bottomSheetDialog.dismiss();


            }
        });

        // 显示BottomSheetDialog
        bottomSheetDialog.show();
    }
    private void showFilter() {
        // 创建BottomSheetDialog
        final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(requireContext());
        View bottomSheetView = getLayoutInflater().inflate(R.layout.layout_filter, null);
        bottomSheetDialog.setContentView(bottomSheetView);
        RadioGroup rg = bottomSheetView.findViewById(R.id.rg_filter);
        Button ok = bottomSheetView.findViewById(R.id.filter_ok);
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rg.getCheckedRadioButtonId() == R.id.income_filter) {
                    billType = 1;
                } else if (rg.getCheckedRadioButtonId() == R.id.expenditures_filter) {
                    billType = 0;
                } else if (rg.getCheckedRadioButtonId() == R.id.all) {
                    billType = -1;
                }
                loadBillData();
                // 关闭对话框
                bottomSheetDialog.dismiss();
            }
        });



        bottomSheetDialog.show();

    }

    @Override
    public void onResume() {
        super.onResume();
        loadBillData();
    }
}
